package com.spzx.product.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.utils.JwtUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.domain.Brand;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import com.spzx.user.api.RemoteUserBrowseHistoryService;
import com.spzx.user.api.domain.UserBrowseHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ChannelServiceImpl implements ChannelService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ProductService productService;
    @Autowired
    private SkuStockService skuStockService;
    @Autowired
    private ProductDetailsService productDetailsService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RemoteUserBrowseHistoryService remoteUserBrowseHistoryService;



    @Override
    public IndexDataVo getIndexData() {
        // 获取首页商品数据
        List<CategoryVo> categoryVoList = categoryService.getLevelOneCategory();// 获取一级分类数据
        List<ProductSkuVo> productSkuVoList = productSkuService.getTopSale();// 获取销量排行前20的商品数据
        IndexDataVo indexDataVo = new IndexDataVo();// 组装数据并返回
        indexDataVo.setCategoryList(categoryVoList);
        indexDataVo.setProductSkuList(productSkuVoList);
        return indexDataVo;
    }

    @Override
    public List<CategoryVo> getCategoryVoList() {

        return categoryService.tree();
    }

    @Override
    public List<Brand> getBrandAll() {
        return brandService.list();
    }

    @Override
    public ItemVo getItemVoBySkuId(Long skuId) {

        ItemVo itemVo = new ItemVo();

        // 异步获取商品信息
        CompletableFuture<Long> futureProductVoSku = CompletableFuture.supplyAsync(() -> {
            //todo 1 获取sku信息
            ProductSkuVo productSkuVo = productSkuService.getProductSkuVoById(skuId);
            itemVo.setProductSku(productSkuVo);
            return productSkuVo.getProductId();

        }, threadPoolExecutor);

        //todo 2 获取sku获取商品最新价格
        CompletableFuture<Void> futureSkuPriceVo = CompletableFuture.runAsync(() -> {
            SkuPriceVo skuPriceVo = productSkuService.getSkuPrice(skuId);
            itemVo.setSkuPrice(skuPriceVo);
        }, threadPoolExecutor);


        //todo 3 获取商品库存信息
        CompletableFuture<Void> futureSkuStockVo = CompletableFuture.runAsync(() -> {
            SkuStockVo skuStockVo = skuStockService.getSkuStock(skuId);
            itemVo.setSkuStock(skuStockVo);
        }, threadPoolExecutor);


        //todo 5. 根据productId获取商品信息
        futureProductVoSku.thenAccept(productId -> {
//        Product product = productService.getById(productId);
            ProductVo productVo = productService.getProductVoById(productId);

            //todo 5.1 根据商品信息：轮播图片列表
            String[] sliderUrlList = productVo.getSliderUrls().split(",");
            itemVo.setSliderUrlList(sliderUrlList);

            //todo 5.2 根据商品信息：规格信息
            // 解析规格信息 JSONArray : 是阿里巴巴的JSON数组 里面有get方法 比如get(int index) getString(int index)等方法
            JSONArray specValueList = JSON.parseArray(productVo.getSpecValue());
            itemVo.setSpecValueList(specValueList);
        });

/*            //todo 4. 获取商品id
            Long productId = productSkuVo.getProductId();*/

        //todo 6. 获取商品详情
        CompletableFuture<Void> futureDetailsImageUrlList = futureProductVoSku.thenAcceptAsync(productId -> {
            String[] detailsImageUrlList = productDetailsService.getDetailsImageUrl(productId);
            itemVo.setDetailsImageUrlList(detailsImageUrlList);
        });

        //todo 7. 获取商品规格对应商品skuId信息Map Key:规格值 value:skuId
        CompletableFuture<Void> futureSkuSpecValueMap = futureProductVoSku.thenAcceptAsync(productId -> {
            Map<String, Long> skuSpecValueMap = productSkuService.getSkuSpecValueMap(productId);
            itemVo.setSkuSpecValueMap(skuSpecValueMap);
        });

        //todo 等待所有异步任务完成
        CompletableFuture.allOf(
                futureProductVoSku,
                futureSkuPriceVo,
                futureSkuStockVo,
                futureDetailsImageUrlList,
                futureSkuSpecValueMap
        ).join();

        //获取登录的用户id
        String token = SecurityUtils.getToken();
        //获取用户id
        String userId = JwtUtils.getUserId(token);
        if(StringUtils.hasText(userId)){
            //创建UserBrowseHistory对象
            UserBrowseHistory userBrowseHistory = new UserBrowseHistory();
            //设置用户id
            userBrowseHistory.setUserId(Long.parseLong(userId));
            //设置商品skuId
            userBrowseHistory.setSkuId(skuId);
            //远程调用用户微服务保存浏览记录
            remoteUserBrowseHistoryService.saveUserBrowseHistory(userBrowseHistory, SecurityConstants.INNER);
        }

        return itemVo;
    }

}
